<template>
  <div class="login">
    <van-form @submit="onSubmit">
      <van-cell-group inset>
        <van-field v-model="username" name="用户名" label="用户名" placeholder="用户名"
          :rules="[{ required: true, message: '请填写用户名' }]"/>
        <van-field v-model="password" type="password" name="密码" label="密码"
          placeholder="密码" :rules="[{ required: true, message: '请填写密码' }]"/>
      </van-cell-group>
      <div style="margin: 16px">
        <van-button round block type="primary" @click="onSubmit" native-type="submit">
          登录
        </van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
import { loginUser } from "@/api/request/login.js";

export default {
  data() {
    return {
      username: "7894561230",
      password: "123456",
      loginUserInfo: {},
    };
  },
  methods: {
    onSubmit() {
      let par = {
        username: this.username,
        password: this.password,
      };
      loginUser(par)
        .then((res) => {
          if (res.status == 200) {
            this.loginUserInfo = res.data.data;
            localStorage.setItem(
              "loginUserInfo",
              JSON.stringify(this.loginUserInfo)
            );
            localStorage.setItem("token", this.loginUserInfo.token);
            // this.connect()
            this.$router.push("/weChat");
          }
        })
        .catch((err) => {
          alert(err);
        });
    },

    connect() {
      // 链接
      console.log("1.开始链接,创建socket");
      manualStop = false;
      window.localStorage.account = "";
      this.socket = new WebSocket(CIM_URI);
      this.socket.cookieEnabled = false;
      this.socket.binaryType = "arraybuffer";
      this.socket.onopen = this.innerOnConnectFinished;
      this.socket.onmessage = this.innerOnMessageReceived;
      this.socket.onclose = this.innerOnConnectionClosed;
    },
    innerOnConnectFinished() {
      // 链接成功回调
      console.log("进入链接成功回调方法");
      let account = window.localStorage.account;
      if (account === "" || account === undefined) {
        account = this.username;
      }
      this.bind(account);
    },
    innerOnMessageReceived(e) {
      // 接收到消息回调
      console.log("socket触发接收消息时间,判断消息类型进行处理");
      let data = new Uint8Array(e.data);
      let type = data[0];
      let body = data.subarray(DATA_HEADER_LENGTH, data.length);

      // 判断消息类型
      if (type === PING) {
        console.log("消息类型--未知");
        this.pong();
        return;
      } else if (type === MESSAGE) {
        // 消息
        console.log("消息类型--普通消息");
        let message =
          proto.com.farsunset.cim.sdk.web.model.Message.deserializeBinary(body);
        this.onInterceptMessageReceived(message.toObject(false));
        return;
      } else if (type === REPLY_BODY) {
        // 账号绑定成功通知
        console.log("消息类型--绑定账号成功通知");
        let message =
          proto.com.farsunset.cim.sdk.web.model.ReplyBody.deserializeBinary(
            body
          );
        /**
         * 将proto对象转换成json对象，去除无用信息
         */
        let reply = {};
        reply.code = message.getCode();
        reply.key = message.getKey();
        reply.message = message.getMessage();
        reply.timestamp = message.getTimestamp();
        reply.data = {};
        /**
         * 注意，遍历map这里的参数 value在前key在后
         */
        message.getDataMap().forEach(function (v, k) {
          reply.data[k] = v;
        });
        if (reply.key === "client_bind" && reply.code === "200") {
          console.log("账号绑定成功");
        }
      }
    },
    innerOnConnectionClosed() {
      // 链接中断回调
      // 中断后循环进行重连
      if (!manualStop) {
        let time = Math.floor(Math.random() * (30 - 15 + 1) + 15);
        setTimeout(function () {
          this.connect();
        }, time);
      }
    },
    bind(account) {
      // 绑定账号
      console.log("进入绑定账号方法");
      window.localStorage.account = account;
      let deviceId = window.localStorage.deviceId;
      if (deviceId === "" || deviceId === undefined) {
        deviceId = generateUUID();
        window.localStorage.deviceId = deviceId;
      }

      let browser = getBrowser();
      let body = new proto.com.farsunset.cim.sdk.web.model.SentBody();
      body.setKey("client_bind");
      body.setTimestamp(new Date().getTime());
      body.getDataMap().set("uid", account);
      body.getDataMap().set("channel", APP_CHANNEL);
      body.getDataMap().set("appVersion", APP_VERSION);
      body.getDataMap().set("osVersion", browser.version);



      body.getDataMap().set("packageName", APP_PACKAGE);
      body.getDataMap().set("deviceId", deviceId);
      body.getDataMap().set("deviceName", browser.name);
      body.getDataMap().set("language", navigator.language);
      this.sendRequest(body);
    },
    sendRequest(body) {
      // 通过websocket绑定用户
      console.log("发送绑定账号请求");
      let data = body.serializeBinary();
      let protobuf = new Uint8Array(data.length + 1);
      protobuf[0] = SENT_BODY;
      protobuf.set(data, 1);
      this.socket.send(protobuf);
    },
    pong() {
      let pong = new Uint8Array(PONG_BODY.byteLength + 1);
      pong[0] = PONG;
      pong.set(PONG_BODY, 1);
      this.socket.send(pong);
    },
    onInterceptMessageReceived(message) {
      // 判断消息类型,做不同的处理
      console.log("进入普通消息处理方法");
      /*
       * 被强制下线之后，不再继续连接服务端
       */
      if (message.action === ACTION_999) {
        manualStop = true;
      }
      //账户在其他地方登录了
      if (message.action === ACTION_999) {
        console.log("你的账号在其他地方登录了!");
        return;
      }
      console.log("你接收到一条消息,消息内容:::", message.content);
    },
    send() {
      // 发送消息
      // TODO 调用后端接口发送消息(http://localhost:5200/gege/api/message/send)
    },
  },
};
</script>

<style>
.login {
  padding: 0;
  margin: auto 0;
}
</style>